package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;

import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;

import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class GeneratePageServiceImpl implements GeneratePageService {
    @Autowired
    Configuration configuration;
    @Resource
    AuthorMapper authorMapper;
    @Resource
    ApArticleMapper apArticleMapper;
    @Resource(name = "minIOFileStorageService")
    private FileStorageService fileStorageService;
    @Value("${file.minio.prefix}")
    private String prefix;

    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {
        if (apArticle == null || apArticle.getAuthorId() == null || StringUtils.isBlank(content)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        try {
//            获取freemarker模板
            Template template = configuration.getTemplate("article.ftl");
            Map map = new HashMap<>();
//            获取作者Id等相关数据
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            if (apAuthor == null){
                log.error("根据文章获取作者ID出错，文章ID为{},作者ID为{}",apArticle.getId(),apArticle.getAuthorId());
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
            }
            map.put("authorApUserId",apArticle.getAuthorId());
            map.put("article",apArticle);
            map.put("content", JSON.parseArray(content,Map.class));
//            注入数据
            StringWriter stringWriter = new StringWriter();
            template.process(map, stringWriter);
//            将静态页存入minIO
            InputStream inputStream = new ByteArrayInputStream(stringWriter.toString().getBytes());
            String path = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", inputStream);
            apArticle.setStaticUrl(path);
            apArticleMapper.updateById(apArticle);
            log.info("静态页写入完成，静态页地址为{}",path);

        } catch (IOException | TemplateException e) {
            e.printStackTrace();
            log.error("文章详情静态页生成失败,articleId : {} ,cause: {}", apArticle.getId(), e.getCause());
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"生成静态页出错");
        }
    }
}
